//
//  SHCashCardViewController.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2017/7/18.
//  Copyright © 2017年 SH_iOS. All rights reserved.
//
//收款卡页面
#import "CSAddButton.h"
#import "BankCardModel.h"
#import "SHBankCarCell.h"
#import "SHChangeCardController.h"
#import "SHAuthFourthStatusPutPhoneController.h"
#import "SHCashCardViewController.h"

@interface SHCashCardViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSMutableArray *bankCardDataArray;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,copy)NSString *bank_card_code;//银行卡号
@property(nonatomic,assign)int bank_card_id;//银行id
@property(nonatomic,strong)UIButton *amendCardBtn;


@end

@implementation SHCashCardViewController


-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
    //添加支付卡成功，接受刷新支付卡列表通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshCashCardNotificationAction:) name:@"refreshCashCardNotification" object:nil];
    
}

#pragma mark - 添加支付卡成功，重新请求数据
- (void)refreshCashCardNotificationAction:(NSNotification *)notification{
    
    [self requstBankCardInfo:YES];
    
    
}


- (NSMutableArray *)bankCardDataArray{
    if (!_bankCardDataArray) {
        _bankCardDataArray = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _bankCardDataArray;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - KNAVIGATIONBARHEIGHT ) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        _tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
        [_tableView registerClass: [SHBankCarCell  class]  forCellReuseIdentifier:@"BankCard"];

    }
    return _tableView;
}


- (CSAddButton *)amendCardBtn{
    
    if (!_amendCardBtn) {
        _amendCardBtn = [[UIButton alloc]init];
        [_amendCardBtn setTitle:@"修改收款卡" forState:UIControlStateNormal];
        [_amendCardBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [_amendCardBtn setTitleColor:KSHTEXTCOLOR forState:UIControlStateNormal];
        [_amendCardBtn addTarget:self action:@selector(amendCardBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        _amendCardBtn.titleLabel.font = KSystemFont(__I6Width(16));
        [self.view addSubview:_amendCardBtn];
//        [_amendCardBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.width.mas_equalTo(__I6Width(96));
//            make.height.mas_equalTo(__I6Height(50));
//            make.centerX.mas_equalTo(self.view.mas_centerX);
//        make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(0);
//        }];
//        
    }
    return _amendCardBtn;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    [self requstBankCardInfo:YES];
    [self refresh];
    
    
    
}
- (void)refresh{
    
    __unsafe_unretained __typeof(self) weakSelf = self;
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf requstBankCardInfo:YES];
        // 马上进入刷新状态
        [weakSelf.tableView.mj_header beginRefreshing];
    }];
    
    
    
    
}


#pragma mark -- 初始化UI
- (void)configUI{

    self.view.backgroundColor = KBASEBGCOLOR;
    [self amendCardBtn];
    
}
#pragma mark -- 获取银行卡信息
- (void)requstBankCardInfo:(BOOL)isRemove{
    
    [SHUserCenterHttp getBankCardLsitWithUsingChoices:1 bankCardType:11 success:^(NSMutableArray *bankCardListArray) {
        if (isRemove) {
            [self.bankCardDataArray removeAllObjects];
            
        }
        for (BankCardModel *model in bankCardListArray) {
            model.using_choices = 1;
            [self.bankCardDataArray addObject:model];
        }
        [self.tableView.mj_header endRefreshing];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            
        });
      

        
    } complection:^(id result) {
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(id erro) {
        [self.tableView.mj_header endRefreshing];
        
    }];
    
    
    
}
#pragma mark --- UITablView  & DataSource  & Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.bankCardDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SHBankCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BankCard"];
    
    BankCardModel *model = self.bankCardDataArray[indexPath.row];
    cell.model = model;
    self.bank_card_code = model.bank_card_code;
    self.bank_card_id = model._id;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return __I6Height(60);
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    
   
    
    //修改
    UITableViewRowAction *editRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"修改" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        /*
         杉德卡，修改使用老接口
         首瀚卡。 修改使用新接口
         */
        //杉德卡不能删除
        BankCardModel *model = self.bankCardDataArray[indexPath.row];

        
        if(model.is_auth == 1 ||model.is_auth == 5){//修改使用银行卡老接口--sd-sh-同步绑卡状态
            
            SHBindCardViewController *bindingBankCardVc = [[SHBindCardViewController  alloc]init];
            bindingBankCardVc.bankCardModel = model;

            bindingBankCardVc.usingType = SHCashCardUsingTypeSdPutCard;
            if (self.push) {
                self.push(bindingBankCardVc);
            }
            
        }else{
            if(model.auth_4_status){//四要素认证通过--银行卡新接口-只能修改手机号
                
                

                SHAuthFourthStatusPutPhoneController *putPhoneVc = [[SHAuthFourthStatusPutPhoneController alloc]init];
                putPhoneVc.bankCardModel = model;
                if (self.push) {
                    self.push(putPhoneVc);
                }

            }else{//四要素认证未通过--银行卡新接口-修改后重新认证
                
                SHBindCardViewController *bindingBankCardVc = [[SHBindCardViewController  alloc]init];
                bindingBankCardVc.bankCardModel = model;
                bindingBankCardVc.usingType = SHCashCardUsingTypeShAgainAuthFouthStatus;
                if (self.push) {
                    self.push(bindingBankCardVc);
                }
            }
            
        }

        
        
        
    }];
    editRowAction.backgroundColor = [UIColor orangeColor];//可以定义RowAction的颜色
    __weak typeof(self)wealkSelf = self;
    //系统
    UITableViewRowAction *deletRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        //杉德卡不能删除
        BankCardModel *model = self.bankCardDataArray[indexPath.row];
        
        if(model.is_auth == 1 ||model.is_auth == 5){//审核通过，审核中----杉德卡
            [self.view makeToast:@"杉德收款卡不能删除" duration:2.f position:@"center"];
            
        }else{
            
            [wealkSelf deleteShCashCard:model];
            
        }

       
    }];
    deletRowAction.backgroundColor = [UIColor redColor];//可以定义RowAction的颜色
    BankCardModel *model = self.bankCardDataArray[indexPath.row];
    
    if(model.is_auth == 1 ||model.is_auth == 5){
        
        return @[deletRowAction];
    }
    return @[deletRowAction,editRowAction];//最后返回这俩个RowAction 的数组
    
}



#pragma mark - 删除收款卡
- (void)deleteShCashCard:(BankCardModel *)model{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [SHUserCenterHttp deleteBankCardWithCardId:model.bank_card_code success:^(id result) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self requstBankCardInfo:YES];
        [_tableView reloadData];
        
    } complection:^(id result) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    } failure:^(id erro) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
    }];
    

}

#pragma mark - 点击cell设为默认卡
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BankCardModel *model = self.bankCardDataArray[indexPath.row];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [SHUserCenterHttp putDefaultBankCardWithCardId:model.bank_card_code usingChoices:1 success:^(id result) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self requstBankCardInfo:YES];
        [self.tableView reloadData];
        
    } complection:^(id result) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];

    } failure:^(id erro) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}



#pragma mark - 修改收款银行卡
- (void)amendCardBtnAction:(CSAddButton *)sender{
    
    SHChangeCardController *changeCardVc = [[SHChangeCardController alloc]init];
    self.push(changeCardVc);
    
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
